package com.ruoyi.web.controller.business;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.dto.ProgressDto;
import com.ruoyi.common.core.domain.entity.CustomerProgress;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Customers;
import com.ruoyi.system.domain.Platforms;
import com.ruoyi.system.domain.vo.ProgressVo;
import com.ruoyi.system.service.ICustomersService;
import com.ruoyi.system.service.IPlatformsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户管理Controller
 * 
 * @author zzbird
 * @date 2023-11-14
 */
@Api("客户管理")
@RestController
@RequestMapping("/business/customers")
public class CustomersController extends BaseController
{
    @Autowired
    private ICustomersService customersService;

    @Autowired
    private IPlatformsService platformsService;

    /**
     * 查询客户管理列表
     */
    @ApiOperation("查询客户管理列表")
    @PreAuthorize("@ss.hasPermi('business:customers:list')")
    @GetMapping("/list")
    public TableDataInfo list(Customers customers)
    {
        startPage();
        List<Customers> list = customersService.selectCustomersList(customers);
        if(list!=null && !list.isEmpty()){
            for (Customers data : list) {
                ProgressDto progressDto = new ProgressDto();
                progressDto.setCustomerId(data.getCustomerId());
                List<Customers> customerDetailList = customersService.getCustomerPlatformsAndProgress(progressDto);
                data.setCustomersDetailList(customerDetailList);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出客户管理列表
     */
    @ApiOperation("导出客户管理列表")
    @PreAuthorize("@ss.hasPermi('business:customers:export')")
    @Log(title = "客户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Customers customers)
    {
        List<Customers> list = customersService.selectCustomersList(customers);
        ExcelUtil<Customers> util = new ExcelUtil<Customers>(Customers.class);
        util.exportExcel(response, list, "客户管理数据");
    }

    /**
     * 获取客户管理详细信息
     */
    @ApiOperation("获取客户管理详细信息")
    @PreAuthorize("@ss.hasPermi('business:customers:query')")
    @GetMapping(value = "/{customerId}")
    public AjaxResult getInfo(@PathVariable("customerId") Long customerId,String platformName)
    {
        Map<String,Object> results = new HashMap<>();
        ProgressDto progressDto = new ProgressDto();
        progressDto.setCustomerId(customerId);
        if(StringUtils.isNotEmpty(platformName)){
            progressDto.setPlatformName(platformName);
        }
        List<CustomerProgress> customerProgressList = new ArrayList<>();
        List<Customers> customersList = customersService.getCustomerPlatformsAndProgress(progressDto);
        if(customersList.isEmpty()){
            Platforms platformsDto = new Platforms();
            List<Platforms> platformsList= platformsService.selectPlatformsList(platformsDto);
            if(!platformsList.isEmpty()){
                for (Platforms platforms : platformsList) {
                    CustomerProgress customerProgress = new CustomerProgress();
                    customerProgress.setCustomerId(customerId);
                    customerProgress.setPlatformId(platforms.getPlatformId());
                    customerProgress.setPlatformName(platforms.getPlatformName());
                    customerProgress.setCurrentProgress(0);//初始化0-未处理
                    customerProgress.setFakeProgress(0);//初始化0-未处理
                    customerProgressList.add(customerProgress);
                }
            }
        }else {
            for (Customers customers : customersList) {
                CustomerProgress customerProgress = new CustomerProgress();
                customerProgress.setCustomerId(customerId);
                customerProgress.setPlatformId(customers.getPlatformId());
                customerProgress.setPlatformName(customers.getPlatformName());
                customerProgress.setCurrentProgress(customers.getCurrentProgress());//初始化0-未处理
                customerProgress.setFakeProgress(customers.getFakeProgress());//初始化0-未处理
                customerProgressList.add(customerProgress);
            }
        }
        results.put("customerProgressList",customerProgressList);
        results.put("customers",customersService.selectCustomersByCustomerId(customerId));
        return success(results);
    }

    /**
     * 新增客户管理
     */
    @ApiOperation("新增客户管理")
    @PreAuthorize("@ss.hasPermi('business:customers:add')")
    @Log(title = "客户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Customers customers)
    {
        System.out.println("当前登录用户名称："+getUsername());
        customers.setCreateBy(getUsername());
        customers.setDeptId(getDeptId());
        customers.setUserId(getUserId());
        return success(customersService.insertCustomers(customers));
    }

    /**
     * 修改客户管理
     */
    @ApiOperation("修改客户管理")
    @PreAuthorize("@ss.hasPermi('business:customers:edit')")
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Customers customers)
    {
        customers.setUpdateBy(getUsername());
        return toAjax(customersService.updateCustomers(customers));
    }

    /**
     * 删除客户管理
     */
    @ApiOperation("删除客户管理")
    @PreAuthorize("@ss.hasPermi('business:customers:remove')")
    @Log(title = "客户管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{customerIds}")
    public AjaxResult remove(@PathVariable Long[] customerIds)
    {
        return toAjax(customersService.deleteCustomersByCustomerIds(customerIds));
    }

    /**
     * 新增平台进度
     */
    @ApiOperation("更新平台进度")
//    @PreAuthorize("@ss.hasPermi('business:customers:addProgress')")
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/addProgress")
    @ResponseBody
    public AjaxResult addProgress(@RequestBody ProgressDto customerProgress)
    {
        if (customerProgress!=null)
        {
            List<Customers> customersList = customersService.getCustomerPlatformsAndProgress(customerProgress);
            if(customersList.size()>0 && customersList !=null){
                if(customerProgress.getFakeProgress() != null){
                    //更新客户显示假进度
                    customersService.updateFakePlatformProgress(customerProgress);
                }else if(customerProgress.getCurrentProgress() != null){
                    //更新真实进度
                    customersService.updatePlatformProgress(customerProgress);
                }
            }else {
                //新增
                customersService.insertPlatformProgress(customerProgress);
            }
            return success();
        }
        return error("更新平台进度失败！");
    }

    @ApiOperation("客户数据导入")
    @Log(title = "客户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('business:customers:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<Customers> util = new ExcelUtil<Customers>(Customers.class);
        List<Customers> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        Long deptId = getDeptId();
        Long userId = getUserId();
        String message = customersService.importCustomer(userList, updateSupport, operName,deptId,userId);
        return success(message);
    }

    @ApiOperation("客户导入模板下载")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<Customers> util = new ExcelUtil<Customers>(Customers.class);
        util.importTemplateExcel(response, "用户数据");
    }
}
